class AutoScrollConstructor {
  constructor() {
    this.raf = null
    this.scroll = null
    this.direction = 1
    this.speed = 2
    this.offset = 5
    this.eventCallback = {
      keypress: e => {
        if (e.key === ' ') {
          if (this.raf === null) {
            this.scroll()
          } else {
            setTimeout(() => {
              this.removeRaf()
            }, 200)
          }
        }
        return e.returnValue = false
      },
      keydown: e => {
        if (['ArrowUp', 'ArrowDown'].includes(e.key)) {
          this.removeRaf()
          if (e.key === 'ArrowUp') {
            /* 上移 */
            this.direction = -1
          } else {
            /* 下移加速 */
            this.speed = 5
          }
          this.scroll()
          return e.returnValue = false
        }
      },
      keyup: e => {
        if (['ArrowUp', 'ArrowDown'].includes(e.key)) {
          this.removeRaf()
          this.scroll()
          return e.returnValue = false
        }
      }
    }
    this.init()
  }

  init() {
    this.scroll = () => {
      let totalHeight /* 页面总高度 */ = document.documentElement.scrollHeight
      let scrollBarHeight /* 滚动条占据高度 */ = document.documentElement.clientHeight
      let scrollBarTop /* 滚动条距顶部距离 */ = document.documentElement.scrollTop
      /* 未滚动到底部 */
      if (totalHeight - scrollBarHeight > scrollBarTop + this.offset) {
        this.raf = window.requestAnimationFrame(this.scroll)
        window.scrollTo(0, scrollBarTop + this.direction * this.speed)
      } else if (this.raf !== null) {
        console.log('到达底部')
        this.removeRaf()
      }
    }
    this.addKeyListener()
    console.log('【自动滚动】准备就绪')
  }

  /* 移除当前raf，并重置 */
  removeRaf() {
    window.cancelAnimationFrame(this.raf)
    this.direction = 1
    this.speed = 2
    this.raf = null
  }

  /* 添加按键监听 */
  addKeyListener() {
    ['keyup', 'keypress', 'keydown'].forEach(eventName => {
      window.addEventListener(eventName, this.eventCallback[eventName])
    })
  }

  /* 撤销按键监听 */
  removeKeyListener() {
    ['keyup', 'keypress', 'keydown'].forEach(eventName => {
      window.removeEventListener(eventName, this.eventCallback[eventName])
    })
  }


  /* 销毁时，撤销全部监听函数 */
  destory() {
    this.removeRaf()
    this.removeKeyListener()
    console.log('【自动滚动】已关闭')
  }
}
